/**
 * 获取host域名
 * @returns
 */
function hostUrl() {
    return location.protocol+'//'+location.host+'/';
}

var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
var isBeiZhu = u.indexOf('BeiZ_Wap/ECCF3EFE2A3E11DAED68A4F63B8E2D14') > -1 || u.indexOf('BeiZ_Wap/ECCF3EFE2A3E11DAED68A4F63B8E2D14') > -1; //是否着想应用内部打开
var isIos = u.indexOf('BeiZ_Wap/ECCF3EFE2A3E11DAED68A4F63B8E2D15') > -1 || u.indexOf('BeiZ_Wap/ECCF3EFE2A3E11DAED68A4F63B8E2D15') > -1; //是否着想应用内部打开

function scenicShare(url, title)
{
	beizhu.BeiZhuShare(url, title);
}
$(document).ready(function(){
	//当在APP内返回首页或我的时返回到原生页面
    $('.sec-head').on('click','a',function(){
        if(isBeiZhu || isIos){
        	var a_href = $(this).attr('href');
        	if(a_href.indexOf('home/home/index') > -1){
        		beizhu.GoToAppHome();
        	}
        	return false;
        }
	});
    
    var hostUrl= location.protocol+'//'+location.host+'/scenic/';
    var status = 'click';
    
    $('body').on('click','.sales-share',function(e) {
    	if(isBeiZhu){
    		var share_url = window.location.href;
        	var share_title = document.title;
        	scenicShare(share_url, share_title);
    	}else{
    		$('.recom-alert').modal();
            var link = $(this).attr('data-link');
            var name = $(this).attr('data-name');
            var img = $(this).attr('data-img');
            $('.am-modal-actions li a').attr('href', link).attr('data-name', name).attr('data-img', img);
    	}
    });
     
     
    //景区首页
    function home()
    {
        $('.sec-color').on(status, '.sec-input', function(event){
            toggle(true, '.main-page', '.minor-page');
            $('.minor-seek').focus();
            event.stopPropagation();
        });
        $('.minor-head').on(status, '.minor-return', function(event){
            toggle(false, '.main-page', '.minor-page');
            event.stopPropagation();
        });
        $('.sec-head').on(status, '.sec-city', function(event){
            toggle(true, '.main-page', '.city-page');
            $('.city-seek').focus();
            event.stopPropagation();
        });
        $('.city-head').on(status, '.city-return', function(event){
            toggle(false,'.main-page', '.city-page');
            event.stopPropagation();
        });
        // 改版景区首页
        $('.newscenic-head').on(status, '.sec-city', function(event){
            toggle(true, '.main-page', '.city-page');
            $('.city-seek').focus();
            event.stopPropagation();
        });
        $('.newscenic-head').on(status, '.search-box', function(event){
            toggle(true, '.main-page', '.minor-page');
            $('.minor-seek').focus();
            event.stopPropagation();
        });
    }

    function toggle(bool, cueClass, pageClass)
    {
        if (bool) {
            $(cueClass).addClass('cue-none');
            $(pageClass).addClass('cue-block');
        } else {
            $(cueClass).removeClass('cue-none');
            $(pageClass).removeClass('cue-block');
        }
    }

    //景区列表页
    var search = {
        urlParams:[],
        ejectOption : function(){//弹出选项
            $('.list-foot').on(status,'.list-target li',function(event){
                $('.list-shade').addClass('am-active');
                var mydata = $(this).data('foot').target;
                $('.list-target li').removeClass('active');
                $('.foot-alert').removeClass('am-modal-active am-animation-slide-bottom');
                $(this).addClass('active');
                $(mydata).addClass('am-modal-active am-animation-slide-bottom');
                $('html,body').addClass('ovfHiden');
                event.stopPropagation();
            });
        },
        shade : function(){//遮罩
            $('body').on(status,'.list-shade',function(event){
                search.initialize();
                event.stopPropagation();
            });
        },
        listSort:function(){//排序
            $('body').on(status,'.alert-list li',function(event){
                $('.alert-list li').removeClass('active');
                $(this).addClass('active');
                search.urlParams['sort'] = $(this).attr('data-id');
                search.elect(this);
                search.initialize();
                //排序表单
                event.stopPropagation();
                search.submit();
            });
        },
        themeOption:function(){//主题选择
            $('body').on(status,'.theme-list li',function(event){
                $('.theme-list li').removeClass('active');
                $(this).addClass('active');
                search.urlParams['theme'] = $(this).attr('data-id');
                search.elect(this);
                search.initialize();
                //主题表单
                event.stopPropagation();
                search.submit();
            });
        },
        useOption:function(){
            $('.foot-three').on(status,'.three-list li',function(event){
                if ($(this).hasClass('active')) {
                    $(this).removeClass('active');
                } else {
                    $(this).addClass('active');
                }
                event.stopPropagation();
            });
        },
        cancel : function(){//取消
            $('.foot-ative').on(status,'.cancel',function(event){
                $('.three-list li').removeClass('active');
                search.initialize();
                event.stopPropagation();
            });
        },
        enter : function(){//确定
            $('.foot-ative').on(status,'.three-active',function(event){
                //表单
                search.initialize();
                search.urlParams['bonus'] = 0; //初始化
                search.urlParams['today'] = 0; //初始化
                search.urlParams['special'] = 0; //初始化
                $('.foot-three .three-list li').each(function(i){
                    if ($(this).hasClass('active')) {
                        if ($(this).attr('data-id') == 'bonus') {
                            search.urlParams['bonus'] = 1;
                        } else if ($(this).attr('data-id') == 'today') {
                            search.urlParams['today'] = 1;
                        } else if ($(this).attr('data-id') == 'special') {
                            search.urlParams['special'] = 1;
                        }
                    }
                });
                search.submit();
                event.stopPropagation();
            });
        },
        initialize : function(){//弹出初始化
            $('.list-shade').removeClass('am-active'); //遮罩
            $('.foot-alert').removeClass('am-modal-active am-animation-slide-bottom');
            $('html,body').removeClass('ovfHiden');
        },
        elect:function(search){
            var electClass = $(search).data('elect').class;
            var electText = $(search).data('elect').text;
            $(electClass).html(electText);
        },
        submit:function(){
            var queries = [];
            for(var key in search.urlParams){
                queries.push(key+'=' + search.urlParams[key]);
            }
            window.location.href = hostUrl + 'search/index?' + queries.join('&');
        },
        getUrlParams:function(){
            search.urlParams['start'] = 0;
            search.urlParams['keyword'] = $('#foot').attr('data-keyword');
            search.urlParams['provinceid'] = $('#foot').attr('data-provinceid');
            search.urlParams['cityid'] = $('#foot').attr('data-cityid');
            $('.foot-one .alert-list li').each(function(){//排序
                if($(this).hasClass('active')){
                    search.urlParams['sort'] = $(this).attr('data-id');
                }
            });
            $('.foot-two .theme-list li').each(function(){//主题
                if($(this).hasClass('active')){
                    search.urlParams['theme'] = $(this).attr('data-id');
                }
            });
            $('.foot-three .three-list li').each(function(i){//是否可用
                if ($(this).hasClass('active')) {
                    if ($(this).attr('data-id') == 'bonus') {
                        search.urlParams['bonus'] = 1;
                    } else if ($(this).attr('data-id') == 'today') {
                        search.urlParams['today'] = 1;
                    } else if ($(this).attr('data-id') == 'special') {
                        search.urlParams['special'] = 1;
                    }
                }
            });
        },
        pageTurning:function(){
            $('#my-scrollspy').scrollspy({
                animation: 'fade',
                delay: 500
            });
            $('#my-scrollspy').on('inview.scrollspy.amui', function() {
                search.urlParams['start'] = search.urlParams['start'] + parseInt(1);
                _this = $(this);
                var queries = [];
                for(var key in search.urlParams){
                    queries.push(key+'=' + search.urlParams[key]);
                }
                $.ajax({
                    type: 'GET',
                    dataType: 'json',
                    url: hostUrl + 'search/ajaxScenery?' + queries.join('&'),
                    success: function(data) {
                        if (data.status) {
                            _this.prev().append(data.html);
                        } else {
                            $('#my-scrollspy').hide();
                        }
                        $('#my-scrollspy').removeClass('am-hide');  
                        $('img.lazy').lazyload();
                    },
                    error : function(jqXHR){
                        console.log(jqXHR.status);
                    }
                });
            });
        },
        init:function(){
            if($('#foot').size()>0){
                var myElement = document.getElementById("foot");
                var headroom  = new Headroom(myElement);
                headroom.init();
            }
            search.pageTurning();
            search.getUrlParams();
            search.ejectOption();
            search.shade();
            search.listSort();
            search.themeOption();
            search.useOption();
            search.cancel();
            search.enter();
        }
    }

    function info()
    {
        $('.vive-nav li').on('open.tabs.amui', function(e) {
            $(window).smoothScroll({position: $('.vive-buy').offset().top});
        })

        //展示更多
        $('.vive-induce').on('click', '#show-more',function(){
            $('.know-hide').html(getInfo());
            $(this).remove();
        });
    }

    if (location.pathname.indexOf('scenic/home') >= 0) { //景区首页
        home();
    } else if (location.pathname.indexOf('scenic/search') >= 0) {//景区列表页
        search.init();
    } else if(location.pathname.indexOf('scenic/info') >= 0) {//景区详情页面
        info();
    }

    /**
     * 景区订单
     */
    var order = {
        page:1,
        type:0,
        ajaxOrder : function(){
            $.ajax({
                type : 'post',
                dataType : 'json',
                async : true,
                data : {page:order.page,type:order.type},
                url : hostUrl + 'order/ajaxOrderList',
                success : function (data){
                    if ( data.possess ) {
                        if ( ! $('#page-empty').hasClass('am-hide') ) {
                            $('#page-empty').addClass('am-hide');
                        }

                        if ( $('#order-list').hasClass('am-hide') ) {
                            $('#order-list').removeClass('am-hide');
                        }

                        if ( data.status) {
                            $('#load-more').removeClass('am-hide');
                            $('.no-more').addClass('am-hide');
                        }else{
                            $('#load-more').addClass('am-hide');
                            $('.no-more').removeClass('am-hide');
                        }
                        order.page++;
                        if ( order.page == 1 ) {
                            $('#order-list').html(data.html);
                        } else {
                            $('#order-list').append(data.html);
                        }
                    } else {
                        $('#page-empty').removeClass('am-hide');
                        $('#order-list').addClass('am-hide');
                        $('#load-more').addClass('am-hide');
                        $('.no-more').addClass('am-hide');
                    }
                }
            });
        },
        orderList : function(){
            $('#order-list').on('click','.code-collection', function(event){
                var type = $(this).data('type');
                var id = $(this).data('id');
                $.ajax({
                    type : 'get',
                    dataType : 'json',
                    async : true,
                    data : {type:type, id:id},
                    url : hostUrl + 'order/getQrcode',
                    success : function (data){
                        if (data.status) {
                            $('#code-collection-modal .am-modal-bd .order-code img').attr('src', data.imgPath);
                            $('#code-collection-modal .am-modal-hd p:eq(0)').text(data.scenicName);
                            $('#code-collection-modal .state').text(data.useStatus);
                            $('#code-collection-modal').modal('open');
                        } else {
                            myalert(data.message);
                        }
                    }
                });
                event.preventDefault();
            });
            $('#order-list-status').on('click', 'dd', function(){
                if ( ! $(this).hasClass('active')) {
                    order.page = 0;
                    order.type = $(this).attr('data-type');
                    $(this).siblings().removeClass('active');
                    $(this).addClass('active');

                    var $w = $(window);
                    $w.smoothScroll({position: 0});
                    order.ajaxOrder();
                }
            });
            $('#load-more').scrollspy({
                animation: 'fade',
                delay: 500
            });
            $('#load-more').on('inview.scrollspy.amui', function() {
               order.ajaxOrder();
            });
        },
        orderRefund:function(){
            $('#secnic-order-refund').on('click', '#submit', function(){
                var number = $('input[name=number]').val();
                var orderId = $('input[name=order_id]').val();
                var maxNum = $('input[name=max_num]').val();

                if (number.length == 0) {
                    myalert('请输入退票数量');
                    return false;
                }
                if ( ! validInt(number)) {
                    myalert('退票数量必须为正整数');
                    return false;
                }
                if (parseInt(number) > parseInt(maxNum)) {
                    myalert('退票数量超出限额');
                    return false;
                }
                var obj = $(this);
                obj.attr('disabled', true);
                $.ajax({
                    type:'post',
                    async:false,
                    dataType:'json',
                    data:{order_id:orderId, goods_num:number},
                    url: hostUrl + 'order/ajaxRefundSubmit',
                    beforeSend:function(){
                        obj.text('正在提交...');
                    },
                    success:function(json){
                        if (json.status) {
                            myalert('退票申请成功');
                            window.location.href = hostUrl+'order/index';
                        } else {
                            myalert(json.message);
                            obj.removeAttr('disabled');
                        }
                        obj.text('提交');
                    }
                });
            });
        },
        orderMofidy:function(){
            $('#secnic-order-modify').on('click', '#submit', function(){
                var plantime = $('input[name=plantime]').val();
                var orderId = $('input[name=order_id]').val();
                var sfz = $('input[name=sfz]').val();
                if ( !checkcard(sfz) ) {
                    myalert('身份证为18位有效的数字');
                    return false;
                }
                var obj = $(this);
                obj.attr('disabled', true);
                $.ajax({
                    type:'post',
                    async:false,
                    dataType:'json',
                    data:{order_id:orderId, plantime:plantime,sfz:sfz},
                    url: hostUrl + 'order/ajaxModifySubmit',
                    beforeSend:function(){
                        obj.text('正在提交...');
                    },
                    success:function(json){
                        if (json.status) {
                            myalert('修改成功');
                            window.location.href = hostUrl+'order/index';
                        } else {
                            myalert(json.message);
                            obj.removeAttr('disabled');
                        }
                        obj.text('提交');
                    }
                });
            });
        },
        orderReviews:function(){
            if($('.mark-ul').size()>0){
                $('.mark-remark').on('click','.mark-ul li',function(event){
                    var text='',
                        index = $(this).index();
                    for(var i=0;i<5;i++){
                        if(i<=index){
                            text += '<li class="active"><i class="iconfont">&#xe623;</i></li>'
                        } else {
                            text += '<li><i class="iconfont">&#xe624;</i></li>'
                        }
                    }
                    $('.mark-ul').html(text);
                    event.stopPropagation();
                });
            }

            $('#order-reviews-submit').click(function(){
                var content = $('textarea[name=content]').val();
                var orderId = $('input[name=order_id]').val();
                var star = 0;
                var obj = $(this);
                $('.mark-ul li').each(function(){
                    if ($(this).hasClass('active')) {
                        star++;
                    }
                });
                if ( isNaN(star) || star < 1) {
                    alertMessage('您还没有为星级打分');
                    return false;
                }
                if (content.length < 15) {
                    alertMessage('您写的点评至少需要15个字');
                    return false;
                }
                $.ajax({
                    type : 'post',
                    dataType : 'json',
                    async : false,
                    data : {order_id:orderId, content:content, star:star},
                    url : hostUrl + 'order/reviewSubmit',
                    beforeSend : function(){
                        obj.attr('disabled', true);
                        obj.text('正在提交...');
                    },
                    success:function(data) {
                        if (data.status) {
                            alertMessage('点评成功');
                            window.location.href = hostUrl+'order/index';
                        } else {
                            alertMessage(data.messages);
                            obj.removeAttr('disabled');
                            obj.text('发表评论');
                        }
                    }
                });
            });
        },
        buyScenicInfor:function(){  //app--购买门票的时候
        	$('.vive-book').on('click','.app-buy',function(){
        		var goodsId = $(this).attr('goods-id');
        		var sid = $(this).attr('sid');
        		beizhu.GoToAPPScenicOrders(goodsId,sid);
        		return false;
        	})
        },
        init : function(){
            if ( $('#order-list-status').size() > 0 ) {
                order.orderList();
            }
            if($('#secnic-order-refund').size() > 0) {
                order.orderRefund();
            }
            if($('#secnic-order-modify').size() > 0) {
                order.orderMofidy();
            }
            if($('#scenic-order-reviews').size() > 0) {
                order.orderReviews();
            }
            if($('.vive-buy .scenic-list').size() > 0) {
            	order.buyScenicInfor();
            }
            
        }
    }
    order.init();
});